package com.jzy.gulimall.product.service.impl;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.common.utils.PageUtils;
import com.jzy.common.utils.Query;
import com.jzy.common.utils.R;
import com.jzy.gulimall.product.dao.SkuInfoDao;
import com.jzy.gulimall.product.entity.SkuImagesEntity;
import com.jzy.gulimall.product.entity.SkuInfoEntity;
import com.jzy.gulimall.product.entity.SpuInfoDescEntity;
import com.jzy.gulimall.product.feign.SeckillFeignService;
import com.jzy.gulimall.product.service.*;
import com.jzy.gulimall.product.vo.SeckillSkuRedisVo;
import com.jzy.gulimall.product.vo.item.SkuItemSaleAttrVo;
import com.jzy.gulimall.product.vo.item.SkuItemVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private AttrGroupService attrGroupService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    /**
     * 商品管理sku 列表
     * page=1&limit=10&key=&catelogId=0&brandId=0&min=0&max=0
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(wrap -> wrap.eq("sku_id", key).or().like("sku_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (StringUtils.isNotBlank(min)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(min);
                if (bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                    wrapper.ge("price", min);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String max = (String) params.get("max");
        if (StringUtils.isNotBlank(max) && !"0".equalsIgnoreCase(max)) {
            wrapper.le("price", max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * spu管理 上架
     * 根据spuId查询对应sku信息
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    /**
     * 详情页 查询sku信息
     * 线程池+异步编排
     */
    @Override
    public SkuItemVo skuItemInfo(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        //1. sku基本信息    pms_sku_info
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = baseMapper.selectById(skuId);
            skuItemVo.setSkuInfoEntity(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        CompletableFuture<Void> skuItemSaleAttrFuture = skuInfoFuture.thenAcceptAsync(resp -> {
            //3. spu销售属性组合
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(resp.getSpuId());
            skuItemVo.setSkuItemSaleAttrVos(skuItemSaleAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> spuInfoDescFuture = skuInfoFuture.thenAcceptAsync((resp) -> {
            //4. spu信息
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(resp.getSpuId());
            skuItemVo.setSpuInfoDescEntity(spuInfoDescEntity);
        }, threadPoolExecutor);

        CompletableFuture<Void> attrGroupFuture = skuInfoFuture.thenAcceptAsync((resp) -> {
            //5. spu规格参数
            List<SkuItemVo.SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupAndAttrBySpuId(resp.getSpuId(), resp.getCatalogId());
            skuItemVo.setSpuItemAttrGroupVos(attrGroupVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            //2. sku图片信息    pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setSkuImagesEntities(skuImagesEntities);
        }, threadPoolExecutor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            //查询当前sku是否参加秒杀优惠
            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (skuSeckillInfo.getCode() == 0) {
                SeckillSkuRedisVo data = skuSeckillInfo.getData(new TypeReference<SeckillSkuRedisVo>() {
                });
                skuItemVo.setSeckillSkuRedisVo(data);
            }
        }, threadPoolExecutor);


        CompletableFuture.allOf(skuItemSaleAttrFuture, spuInfoDescFuture, attrGroupFuture, skuImagesFuture, seckillFuture).get();
        return skuItemVo;
    }

}